//TODO: LeetCode2. 两数相加
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

//* Ver1
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* ret = nullptr;
        ListNode* cur = ret;
        int flag = 0;

        while(l1 || l2 || flag) {
            int x1 = l1 == nullptr ? 0 : l1->val;
            int x2 = l2 == nullptr ? 0 : l2->val;

            int sum = x1 + x2 + flag;
            flag = sum / 10;
            sum %= 10;

            if (ret == nullptr) {
                ret = new ListNode(sum);
                cur = ret;
            }
            else {
                ListNode* next = new ListNode(sum);
                cur->next = next;
                cur = next;
            }

            l1 = l1 == nullptr ? nullptr : l1->next;
            l2 = l2 == nullptr ? nullptr : l2->next;
        }

        return ret;
    }
};

//* Ver2
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* temp = new ListNode;
        ListNode* cur = temp;
        int flag = 0;

        while(l1 || l2 || flag) {
            int x1 = l1 == nullptr ? 0 : l1->val;
            int x2 = l2 == nullptr ? 0 : l2->val;

            int sum = x1 + x2 + flag;
            flag = sum / 10;
            sum %= 10;

            ListNode* next = new ListNode(sum);
            cur->next = next;
            cur = next;

            l1 = l1 == nullptr ? nullptr : l1->next;
            l2 = l2 == nullptr ? nullptr : l2->next;
        }

        ListNode* ret = temp->next;
        delete temp;
        return ret;
    }
};